package com.example.demoeasyexcelboot.controller;

import com.example.demoeasyexcelboot.annotation.FileCheck;
import com.example.demoeasyexcelboot.commons.EasyExcelUtil;
import com.example.demoeasyexcelboot.constants.FileType;
import com.example.demoeasyexcelboot.dto.UserDto;
import com.example.demoeasyexcelboot.excel.ImportExcelResult;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author: FSL
 * @date: 2023/4/12
 * @description: 导入导出接口
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    private static List<UserDto> userDtoList = new ArrayList<>(10);
    static {
        UserDto userDto;
        Random random = new Random();
        for (int i = 0;i < 10; i++){
            int anInt = random.nextInt(3);
            userDto = UserDto.builder().id((long) i)
                    .email("fengsulin@163.com")
                    .username("wahaha")
                    .birthday(new Date())
                    .groupId((long)(anInt))
                    .phone("18311787878")
                    .height(random.nextDouble() * 100)
                    .gender(1)
                    .build();
            userDtoList.add(userDto);
        }
        Collections.sort(userDtoList,Comparator.comparingLong(UserDto::getGroupId));
    }
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        EasyExcelUtil.writeExcel(response,"test-export",userDtoList,UserDto.class,"测试表");
    }

    @PostMapping("/upload")
    @FileCheck(type = FileCheck.CheckType.SUFFIX_MAGIC_NUMBER,fileTypes = {FileType.XLS,FileType.XLSX})
    public ImportExcelResult upload(MultipartFile file) throws IOException {
        ImportExcelResult importExcelResult = EasyExcelUtil.readExcel(file.getInputStream(), UserDto.class);
        return importExcelResult;
    }
}
